#include<iostream>
#include<cstdio>
#include<cerrno>
#include<string>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>

void SetNonBlock(int fd)
{
    int flags = fcntl(fd, F_GETFL, 0);
    if(flags < 0){
        std::cout<<"fcntl get flags error"<<std::endl;
        return;
    }
    fcntl(fd, F_SETFL, flags | O_NONBLOCK);//设置非阻塞
}

int main()
{
    SetNonBlock(0);//设置标准输入为非阻塞
    std::string tips = "Please Enter#";
    char buffer[1024];
    while(true){
        write(1,tips.c_str(),tips.size());//输出提示信息
        int n = read(0,buffer,sizeof(buffer));
        if(n>0){
            buffer[n] = '\0';
            std::cout<<"echo#"<<buffer;
        }else if(n==0){
            std::cout<<"read file end"<<std::endl;
        }else{
            std::cout<<"read error: "<<n << " errno: "<<errno<<std::endl;
            if(errno == EAGAIN || errno == EWOULDBLOCK){//#define	EAGAIN  11	/* Try again */  #define  EWOULDBLOCK	EAGAIN	/* Operation would block */
                //do other things
                std::cout<<"底层数据没有准备好: try again"<<std::endl;
                sleep(1);
                continue;
            }
            else if(errno == EINTR){//#define	EINTR   4	/* Interrupted system call */被信号中断
                std::cout<<"被中断，重新进行 "<<std::endl;
                sleep(1);
                continue;
            }
            
        }
        sleep(1);
    }
    return 0;
}